
'use strict';
import React from 'react'
import { Image } from 'react-native';
import RouterHelper from './RouterHelper'
import hoistNonReactStatics from 'hoist-non-react-statics'

export const tabOptions = (params) => {
    return {
        title: params.title,
        tabBarIcon: ({ focused, tintColor }) => (
            <Image
                resizeMode={'contain'}
                style={{ width: ScaleSize(40), height: ScaleSize(40) }}
                source={!focused ? params.normalIcon : params.selectedIcon}
            />
        )
    }
};

export const configRouter = (routeConfig) => {
    for (let name in routeConfig) {
        let Component = routeConfig[name].screen;
        routeConfig[name].screen = createNavigationContainer(Component)
    }
    return routeConfig
}

// 高阶组件
export const createNavigationContainer = (OldComponent) => {

    class NewComponent extends React.PureComponent {

        static displayName = `todoNavigationContainer(${OldComponent.displayName ||
            OldComponent.name})`;

        constructor(props) {
            super(props)
            // this.subscriptions = []
        }

        componentDidMount() {
            requestAnimationFrame(() => {
                this._addNavigation()
            })
        };

        componentWillUnmount() {
            requestAnimationFrame(() => {
                this._removeNavigation()
            })
        };

        _addNavigation = () => {
            const { navigation } = this.props
            RouterHelper.addStack(navigation);
        }

        _removeNavigation = () => {
            const { navigation } = this.props
            RouterHelper.remove(navigation);
        }

        _captureRef = (node) => {
            if (node) {
                // bind native component's methods
                for (let methodName in node) {
                    const method = node[methodName];
                    if (!methodName.startsWith('_') && // private methods
                        !methodName.startsWith('component') && // lifecycle methods
                        typeof method === 'function' &&
                        this[methodName] === undefined) {
                        this[methodName] = method;
                    }
                }
                this._oldComponentRef = node
            }
        };

        render() {
            return (
                <OldComponent
                    ref={this._captureRef}
                    {...this.props}
                />
            )
        }
    }

    return hoistNonReactStatics(NewComponent, OldComponent)
};
